<template>
  <div>
    <el-drawer v-model="dialog.visible" width="800px" :title="dialog.title" destroyOnClose>
      <div class="box">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120" validateOnRuleChange>
          <div class="block" v-for="(item, index) in config" :key="index">
            <div v-if="item.show">
              <div class="title">{{ item.label }}</div>
              <div class="subitembox">
                <div class="subitem" v-for="(subitem, subindex) in item.list" :key="subindex">
                  <div v-if="subitem.show">
                    <el-form-item
                      v-if="
                        (subitem.field === 'productId' && form['relatedProduct']['productSetting'] === 'SINGLE') ||
                        (subitem.field === 'deepExternalAction' &&
                          form[subitem.supField]['externalAction'] &&
                          form['microPromotionType'] !== 'WECHAT_APP' &&
                          form[subitem.supField]['externalAction'] !== 'TYPE_GAME_ADDICTION') ||
                        (subitem.field === 'cpaBid' && form[subitem.supField]['bidType'] === 'CUSTOM' && form['microPromotionType'] !== 'AWEME') ||
                        (subitem.field === 'roiGoal' &&
                          (form['optimizeGoal']['deepExternalAction'] === 'TYPE_LT_ROI' ||
                            form['optimizeGoal']['deepExternalAction'] === 'TYPE_PURCHASE_ROI') &&
                          form[subitem.supField]['bidType'] !== 'NO_BID') ||
                        (subitem.field === 'microAppInstanceId' && form['microPromotionType'] !== 'AWEME') ||
                        (subitem.field != 'deepExternalAction' &&
                          subitem.field !== 'cpaBid' &&
                          subitem.field !== 'roiGoal' &&
                          subitem.field !== 'microAppInstanceId' &&
                          subitem.field !== 'productId')
                      "
                      :prop="subitem.supField ? `${subitem.supField}.${subitem.field}` : subitem.field"
                    >
                      <template #label>
                        <div class="label">
                          {{ subitem.label }}

                          <!-- {{ renderLabel(subitem) }} -->
                        </div>
                      </template>
                      <div class="flex listbox" v-if="subitem.list && subitem.list.length && subitem.type === 'radio'">
                        <div
                          class="listItem"
                          v-for="(thitem, thindex) in subitem.list"
                          :key="thindex"
                          :class="[
                            (form[subitem.supField] && subitem.field === 'platform' && form[subitem.supField][subitem.field][0] == thitem.value[0]) ||
                            (form[subitem.supField] ? form[subitem.supField][subitem.field] : form[subitem.field]) == thitem.value ||
                            (!subitem.field && thindex === 0)
                              ? 'active'
                              : '',
                            subitem.list.length === 1 ? 'onlyOne' : ''
                          ]"
                          @click="setValue(subitem, thitem.value, subitem.isCanSelect)"
                        >
                          {{ thitem.label }}
                        </div>
                      </div>
                      <!-- 多选年龄 -->
                      <div class="mt-[5px] w-full" v-if="subitem.field === 'age'">
                        <div class="flex listbox" v-if="subitem.field === 'age' && subitem.type === 'checkbox'">
                          <!-- <el-checkbox-group class="flex" v-model="selectAges" @change="handleAgeChange($event, subitem.list)">
                            <div class="mr-[10px]" v-for="(itm, idx) in subitem.list" :key="idx">
                              <el-checkbox-button :label="itm.label" :value="itm.value" :disabled="itm.disabled">
                                {{ itm.label }}
                              </el-checkbox-button>
                            </div>
                          </el-checkbox-group> -->
                          <div
                            class="listItem"
                            v-for="(thitem, thindex) in subitem.list"
                            :key="thindex"
                            :class="[selectAges.length === 0 && thindex === 0 ? 'active' : '', selectAges.includes(thitem.value) ? 'active' : '']"
                            @click="handleAgeChange(subitem.list, thindex)"
                          >
                            {{ thitem.label }}
                          </div>
                        </div>
                      </div>
                      <!-- 行政区域 -->
                      <div class="mt-[5px] w-full" v-if="subitem.field === 'district'">
                        <div class="addresslistbox" v-if="(subitem.field === 'district' && form[subitem.supField]['district']) === 'REGION'">
                          <div class="w-full h-[200px] overflow-y-scroll addressSelect">
                            <div class="items">
                              <el-checkbox-group v-model="addressIsAllValue" @change="handleAllSelect">
                                <el-checkbox label="全选" value="ALL" :indeterminate="isIndeterminate" />
                              </el-checkbox-group>
                            </div>
                            <el-checkbox-group v-model="form[subitem.supField]['city']">
                              <div class="items" v-for="(addItem, addIndex) in addressList" :key="addIndex">
                                <el-checkbox :label="addItem.label" :value="addItem.value" />
                              </div>
                            </el-checkbox-group>
                          </div>
                          <div class="mt-[5px] info">
                            <div class="label">地域类型：</div>
                            <div class="val">
                              <el-radio-group v-model="form[subitem.supField]['locationType']">
                                <el-radio value="CURRENT" label="正在该地区的用户"></el-radio>
                                <el-radio value="HOME" label="居住在该地区的用户"></el-radio>
                                <el-radio value="TRAVEL" label="到该地区旅行的用户"></el-radio>
                                <el-radio value="ALL" label="该地区内的所有用户"></el-radio>
                              </el-radio-group>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 出价 -->
                      <div
                        class="w-[300px] inputbox"
                        v-if="subitem.type === 'input' && subitem.field === 'cpaBid' && form[subitem.supField]['bidType'] === 'CUSTOM'"
                      >
                        <el-input
                          v-model="form[subitem.supField][subitem.field]"
                          :type="subitem.inputType ? subitem.inputType : ''"
                          :placeholder="`请输入${subitem.label}`"
                          :min="subitem.min"
                          :max="subitem.max"
                        ></el-input>
                        <br />
                        <div class="text-[12px] text-[#197afb] tips">{{ subitem.tips }}</div>
                      </div>
                      <!-- ROI系数 -->
                      <div
                        class="w-[300px] inputbox"
                        v-if="
                          subitem.type === 'input' &&
                          subitem.field === 'roiGoal' &&
                          (form['optimizeGoal']['deepExternalAction'] === 'TYPE_LT_ROI' ||
                            form['optimizeGoal']['deepExternalAction'] === 'TYPE_PURCHASE_ROI')
                        "
                      >
                        <el-input
                          v-model="form[subitem.supField][subitem.field]"
                          :type="subitem.inputType ? subitem.inputType : ''"
                          :placeholder="`请输入${subitem.label}`"
                          :min="subitem.min"
                          :max="subitem.max"
                        ></el-input>
                        <br />
                        <div class="text-[12px] text-[#197afb] tips">{{ subitem.tips }}</div>
                      </div>
                      <div
                        class="w-[300px] inputbox"
                        v-if="subitem.type === 'input' && subitem.field !== 'cpaBid' && subitem.field !== 'roiGoal' && !subitem.supField"
                      >
                        <el-input
                          v-model="form[subitem.field]"
                          :type="subitem.inputType ? subitem.inputType : ''"
                          :placeholder="`请输入${subitem.label}`"
                          :min="subitem.min"
                          :max="subitem.max"
                        ></el-input>
                        <br />
                        <div class="text-[12px] text-[#197afb] tips">{{ subitem.tips }}</div>
                      </div>
                      <div
                        class="w-[300px] inputbox"
                        v-if="subitem.type === 'input' && subitem.field !== 'cpaBid' && subitem.field !== 'roiGoal' && subitem.supField"
                      >
                        <el-input
                          v-model="form[subitem.supField][subitem.field]"
                          :type="subitem.inputType ? subitem.inputType : ''"
                          :placeholder="`请输入${subitem.label}`"
                          :min="subitem.min"
                          :max="subitem.max"
                        ></el-input>
                        <br />
                        <div class="text-[12px] text-[#197afb] tips">{{ subitem.tips }}</div>
                      </div>
                      <!-- 优化目标 -->
                      <div class="flex w-[300px] listbox" v-if="subitem.type === 'select' && subitem.list && subitem.field === 'externalAction'">
                        <el-select v-model="form[subitem.supField][subitem.field]">
                          <el-option
                            v-for="(sitem, sindex) in externalActionListRes?.goals"
                            :key="sindex"
                            :label="sitem.optimizationName"
                            :value="sitem.externalAction"
                          ></el-option>
                        </el-select>
                      </div>

                      <!-- 深度优化目标 -->
                      <div
                        class="flex w-[300px] listbox"
                        v-if="subitem.type === 'select' && form[subitem.supField]['externalAction'] && subitem.field === 'deepExternalAction'"
                      >
                        <el-select v-model="form[subitem.supField][subitem.field]">
                          <el-option v-for="(sitem, sindex) in subitem.list" :key="sindex" :label="sitem.label" :value="sitem.value"></el-option>
                        </el-select>
                      </div>

                      <!-- 投放时间设置 -->
                      <div
                        class="w-full mt-[15px] timeset"
                        v-if="subitem.field === 'scheduleType' && form[subitem.supField][subitem.field] === 'START_END'"
                      >
                        <el-date-picker
                          v-model="deliverDate"
                          type="daterange"
                          value-format="YYYY-MM-DD"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                        />
                      </div>
                      <div class="w-full mt-[15px] timeset" v-if="subitem.field === 'scheduleTimeType' && form[subitem.supField][subitem.field] === 1">
                        <TimeSelect ref="'timeSelectRef'" @get-value="(val) => getTimeValue(val, subitem.supField, 'scheduleTime')" />
                      </div>

                      <!-- 投放版位媒体选择 -->
                      <div class="mt-[15px] w-full"  v-if="subitem.field ==='inventoryCatalog'">
                        <div
                          class="flex w-[300px] listbox"
                          v-if="subitem.field ==='inventoryCatalog' && form[subitem.supField]['inventoryCatalog'] === 'MANUAL'"
                        >
                          <el-select v-model="form[subitem.supField]['inventoryType']" :multiple="true" placeholder="请选择">
                            <el-option label="抖音" value="INVENTORY_AWEME_FEED"></el-option>
                          </el-select>
                        </div>
                      </div>
                    
                    

                      <!-- 组件调用 -->
                      <div class="w-full compoents" v-if="subitem.type === 'components'">
                        <!-- 短剧选择组件 -->
                        <div class="w-[300px] btnType" v-if="subitem.openType === 'button' && subitem.componentRef === 'dramaRef'">
                          <div
                            class="cursor-pointer text-[12px] bg-[#197AFB] text-[#fff] rounded-[4px] btn"
                            v-if="subitem.supField ? !form[subitem.supField][subitem.field] : !form[subitem.field]"
                            @click="openComponent(subitem.componentRef)"
                          >
                            {{ subitem.openText }}
                          </div>
                          <div
                            v-else
                            class="border-solid border-1px border-[#197AFB] cursor-pointer bg-[#d6eaff] text-[#197AFB] w-[400px] px-[10px] rounded-[4px]"
                            @click="openComponent(subitem.componentRef)"
                          >
                            {{ subitem.supField ? form[subitem.supField][subitem.showField] : form[subitem.field] }}
                          </div>
                        </div>
                        <!-- 小程序选择组件 -->
                        <div
                          class="w-[300px] btnType"
                          v-if="subitem.openType === 'button' && subitem.componentRef === 'microAppRef' && form['microPromotionType'] !== 'AWEME'"
                        >
                          <div class="cursor-pointer text-[12px] bg-[#197AFB] text-[#fff] rounded-[4px] btn" @click="openComponent(subitem.componentRef)">
                            {{ form[subitem.changeCondition] === 'WECHAT_APP' ? '选择微信小程序' : '选择字节小程序' }}
                          </div>
                        </div>
                        <!-- 小程序信息显示 -->
                        <div
                          class="mt-[15px] w-full"
                          v-if="subitem.openType === 'button' && subitem.componentRef === 'microAppRef' && form.userInfo && form.userInfo[0]?.appId"
                        >
                          <div class="w-full userbox">
                            <div class="w-full bg-[#FAFAFA] flex userheader">
                              <div class="w-[50%] px-[15px] py-[2px] col">账户</div>
                              <div class="w-[50%] px-[15px] py-[2px] col">
                                {{ form[subitem.changeCondition] === 'WECHAT_APP' ? '微信小程序' : '字节小程序' }}
                              </div>
                            </div>
                            <div class="flex w-full list" v-for="(item, index) in form.userInfo" :key="index">
                              <div class="w-[50%] flex px-[15px] py-[8px] flex-col col">
                                <span class="text-[12px] leading-[20px] account">{{ item.name }}</span>
                                <span class="text-[12px] leading-[20px] text-[#ccc] account">{{ item.id }}</span>
                              </div>
                              <div class="w-[50%] flex px-[15px] py-[8px] flex-col col">
                                <span class="text-[12px] leading-[20px] account">名称：{{ item.appName }}</span>
                                <span class="text-[12px] leading-[20px] account">ID:{{ item.appId }}</span>
                              </div>
                            </div>
                          </div>
                        </div>
                        
                      </div>
                    </el-form-item>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div class="w-full btnbox">
          <el-button  @click="hide">取消</el-button>
          <el-button  type="primary" @click="submitData">保存</el-button>
        </div>
      </template>
    </el-drawer>
    <Drama ref="dramaRef" :advertiserId="props.userList" :productId="form.relatedProduct.productId" @getProduct="getProductInfo" />
    <Micoapp ref="mircoappRef" v-if="showMicoapp" :advertiserId="props.userList" :type="mircoAppType" @getAppInfo="getAppInfo" />
  </div>
</template>

<script setup lang="ts">
import { ProjectConfig, type ProjectForm, initFormData, type Item, type Option, ProjectRules } from '@/config/project';
import { useAppStore } from '@/store/modules/app';
import { queryToolsMicroAppNew, getAllWechatApplet } from '@/api/com';
import {
  getEventManagerOptimizedGoal,
  type ManagerOptimizedGoalQuery,
  type ManagerOptimizedGoalData,
  type ManagerOptimizedGoalVO,
  type EventManagerDeepBidTypeQuery,
  getAddressListInfo
} from '@/api/com';
import { fromType } from 'vue-types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const showMicoapp = ref(false);
const showDrama = ref(false);

type SelectAccountType = {
  id: number | string;
  name: string;
};

type SelectAppInfoType = {
  id: number | string;
  name: string;
  appId?: string;
  appName?: string;
  assetId?: number;
};

const props = defineProps<{
  userList: SelectAccountType[];
  project: object;
}>();

const emit = defineEmits(['getValue', 'updateInfo']);

const appStore = useAppStore();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '创建项目'
});

const formRef = ref();

const rules = ProjectRules;

const addressList = ref([]);

const addressIsAllValue = ref([]);

const selectAges = ref([]);

const isIndeterminate = ref(false);

const remoteLoading = ref(false);

const config = ref(ProjectConfig);

const externalActionListRes = ref<ManagerOptimizedGoalData>({
  assetIds: undefined,
  goals: []
});

const externalActionList = ref<ManagerOptimizedGoalVO[]>([]);

const deliverDate = ref<string[]>([]);

const dramaRef = ref(null);

const mircoappRef = ref(null);

const timeSelectRef = ref(null);

const mircoAppType = ref<string>('WECHAT_APP');

const form = ref<ProjectForm>(JSON.parse(JSON.stringify(initFormData)));

const setValue = (item: Item, value: string | number | boolean | string[], isCanSelect: boolean) => {
  if (isCanSelect && item.field) {
    if (item.field === 'platfrom') {
      form.value[item.supField][item.field] = value ? [value] : undefined;
    } else {
      item.supField ? (form.value[item.supField][item.field] = value) : (form.value[item.field] = value);
    }
    if (item.field === 'microPromotionType') {
      // 切换投放载体时，清空已选小程序信息
      mircoAppType.value = value as string;
      props.userList.map((item, index) => {
        item.appId = undefined;
        item.appName = undefined;
        item.instanceId = undefined;
        item.assetId = undefined;
      });
      form.value.userInfo &&
        form.value.userInfo.map((item, index) => {
          item.appId = undefined;
          item.appName = undefined;
          item.instanceId = undefined;
          item.assetId = undefined;
        });
      form.value['optimizeGoal']['externalAction'] = null;
      form.value['optimizeGoal']['deepExternalAction'] = null;

      //字节小程序清除事件
      if (mircoAppType.value !== 'BYTE_APP') {
        form.value['optimizeGoal']['assetIds'] = null;
      }
      if (mircoAppType.value != 'AWEME') {
        externalActionListRes.value = {
          assetIds: undefined,
          goals: []
        };
        mircoappRef.value?.clearAll();
      } else {
        awemeDeepSet();
      }
      // if (mircoAppType.value === 'WECHAT_APP') {
      //   form.value['optimizeGoal']['deepExternalAction'] = null;
      // }
    }
    if(item.field ==='deliveryMode'){
      handleItemsChange()
    }
    if(item.field === 'bidType'){
      handleItemsChange()
    }
    if(item.field === 'inventoryCatalog'){
      handleItemsChange()
    }
  }
};

// const handleAgeChange = (selectedValues: string[], list: any[]) => {
//   // 判断是否选中了第 0 项
//   const isFirstItemSelected = selectedValues.includes(list[0].value);
//   list.forEach((item, idx) => {
//     if (idx === 0) {
//       // 如果第 0 项被选中，禁用其他选项
//       if (isFirstItemSelected) {
//         list.forEach((j, jIdx) => {
//           if (jIdx !== 0) j.disabled = true;
//         });
//       } else {
//         // 如果第 0 项取消选中，启用所有选项
//         list.forEach((j) => (j.disabled = false));
//       }
//     } else {
//       // 如果其他项被选中，禁用第 0 项
//       if (selectedValues.includes(item.value)) {
//         list[0].disabled = true;
//       }
//     }
//   });
// };


const handleItemsChange = ()=>{
  if(form.value.deliveryMode === 'MANUAL'){
      
      if(!form.value.audience.interestActionMode){
        form.value.audience.interestActionMode = 'UNLIMITED'
      }
      if(form.value.aigcDynamicCreativeSwitch){
        form.value.aigcDynamicCreativeSwitch = 'OFF'
      }
      //手动投放
      config.value[2].show = false;
      config.value[4].show = true;
      config.value[5].list.map((subitem)=>{
        if(subitem.field === "interestActionMode"){
          subitem.show = true
        }
      })
      config.value[6].list.map((subitem)=>{
        if(subitem.field === "bidType"){
          subitem.list = [
            {
              label: '稳定成本',
              value: 'CUSTOM'
            },
            {
              label: '最优成本',
              value: 'UPPER_CONTROL'
            },
            {
              label: '最大转化',
              value: 'NO_BID'
            }
          ]
        }
        if(subitem.field === "searchBidRatio" || subitem.field === "audienceExtend"){
          subitem.show = true
        }
        if(subitem.field === "cpaBid"){
          subitem.show = false
        }
      })
    
  }else if(form.value.deliveryMode === 'PROCEDURAL'){
    //自动投放
    form.value.audience.interestActionMode = undefined
    if(!form.value.aigcDynamicCreativeSwitch){
      form.value.aigcDynamicCreativeSwitch = 'OFF'
    }
    config.value[2].show = true;
    config.value[4].show = false;
    config.value[5].list.map((subitem)=>{
      if(subitem.field === "interestActionMode"){
        subitem.show = false
      }
    })
    
    config.value[6].list.map((subitem)=>{
      if(subitem.field === "bidType"){
        subitem.list = [
          {
            label: '稳定成本',
            value: 'CUSTOM'
          },
          {
            label: '最大转化',
            value: 'NO_BID'
          }
        ]
      }
      if(subitem.field === "searchBidRatio" || subitem.field === "audienceExtend"){
        subitem.show = false
      }
      if(subitem.field === "cpaBid"){
        subitem.show = true
      }
    })
    form.value['audience']['interestActionMode'] = undefined
  }

  if(form.value.deliverySetting.bidType === 'NO_BID'){
    form.value.deliverySetting.budgetOptimizeSwitch = 'OFF'
    config.value[6].list.map((subitem)=>{
      if(subitem.field === "budgetOptimizeSwitch") {
        subitem.show = true
      }
    }) 
  }else {
    form.value.deliverySetting.budgetOptimizeSwitch = undefined
    config.value[6].list.map((subitem)=>{
      if(subitem.field === "budgetOptimizeSwitch") {
        subitem.show = false
      }
    }) 
  }

  if(form.value.deliveryRange.inventoryCatalog === 'UNIVERSAL_SMART'){
    form.value.deliveryRange.inventoryType = undefined
  }
}

const handleAgeChange = (list: any[], index: number) => {
  if (index === 0) {
    selectAges.value = [];
  } else {
    const inIndex = selectAges.value.indexOf(list[index].value);
    if (inIndex !== -1) {
      selectAges.value.splice(inIndex, 1);
    } else {
      selectAges.value.push(list[index].value);
    }
  }
};

const openComponent = (ref: string) => {
  showMicoapp.value = true;
  setTimeout(() => {
    if (ref === 'dramaRef' && dramaRef.value) {
      showDrama.value = true;
      dramaRef.value?.show();
    } else if (ref === 'microAppRef' && mircoappRef.value) {
      form.value.optimizeGoal.assetIds = null;
      mircoappRef.value?.show();
      mircoappRef.value?.init();
    }
  }, 200);
};

/**
 *  获取时间段选择值
 */
const getTimeValue = (val: string, parent: string, cur: string) => {
  form.value[parent][cur] = val;
};

/**
 * 获取产品信息
 */
const getProductInfo = (val) => {
  form.value.relatedProduct.productPlatformId = val.productPlatformId;
  form.value.relatedProduct.productId = val.productId;
  form.value.relatedProduct.productName = val.productName;
};

/**
 * 投放载体变化时需要重新获取优化目标
 */
const getExternalAction = async () => {
  if (form.value['microPromotionType'] === 'BYTE_APP') {
    if (!form.value.userInfo) {
      // proxy?.$modal.msgError('请先选择字节小程序');
      return;
    }
  }
  if (form.value['microPromotionType'] === 'AWEME') {
    awemeDeepSet();
  } else {
    remoteLoading.value = true;
    const res = await getEventManagerOptimizedGoal({
      pageNum: 1,
      pageSize: 100,
      accountId: appStore.accountId,
      advertiserId: props.userList[0]?.id as number,
      // advertiserId: 1826828145990666,
      landingType: form.value['landingType'],
      deliveryMode: form.value['deliveryMode'],
      adType: form.value['adType'],
      assetType: form.value['microPromotionType'] === 'WECHAT_APP' ? 'WECHAT_APP' : 'MICRO_APP',
      microAppInstanceId:
        form.value['microPromotionType'] === 'WECHAT_APP' ? undefined : form.value.userInfo ? (form.value.userInfo[0].instanceId as string) : ''
    });
    externalActionListRes.value = res.data;
    remoteLoading.value = false;
  }
};

/**
 * 抖音号优化设置
 */
const awemeDeepSet = () => {
  nextTick(() => {
    // console.log('抖音号优化设置', externalActionListRes.value);
    externalActionListRes.value.goals = [
      {
        optimizationName: '激活',
        externalAction: 'TYPE_ACTIVE'
      }
    ];
    awemeSetDeepList();
  });
};

const awemeSetDeepList = () => {
  config.value.map((item) => {
    item.list.map((subitem, subindex) => {
      if (subitem.field === 'deepExternalAction') {
        // subitem.list = [];
        // form.value[subitem.supField][subitem.field] = null;
        subitem.list = [
          {
            label: '广告变现ROI',
            value: 'TYPE_LT_ROI'
          }
        ];
      }
    });
  });
};

watch(
  () => props.project,
  () => {
    nextTick(() => {
      if (props.project) {
        mircoAppType.value = props.project?.microPromotionType;
        form.value = props.project;
        handleItemsChange()
        form.value.audience.age = props.project.age
          ? props.project.age.split(',')
          : (selectAges.value = selectAges.value.filter((item) => item.trim() !== ''));
        if (props.project?.userInfo && form.value.userInfo[0].instanceId && form.value.microPromotionType !== 'AWEME') {
          getExternalAction();
        }
        if (form.value.microPromotionType === 'AWEME') {
          externalActionListRes.value = {
            assetIds: undefined,
            goals: []
          };
          awemeDeepSet();
        }
        if(props.project?.deliveryRange.inventoryCatalog === "MANUAL"){

        }
      } else {
        form.value = JSON.parse(JSON.stringify(initFormData));
      }
      form.value.projectProductWay = 1;

      // console.log(form.value.audience.platform, 'form.value.audience.platform');
    });
  },
  { immediate: true }
);

//监听投放内容变化
watch(
  () => form.value['microPromotionType'],
  () => {
    nextTick(() => {
      if (form.value['microPromotionType'] !== 'AWEME') {
        form.value['deliverySetting']['deepBidType'] = 'ROI_COEFFICIENT';
        if (form.value['microPromotionType'] === 'WECHAT_APP') {
          form.value['optimizeGoal']['deepExternalAction'] = null;
          form.value['deliverySetting']['deepBidType'] = null;
          form.value['deliverySetting']['roiGoal'] = null;
        }
        if (form.value.userInfo && form.value.userInfo[0]?.appId) {
          getExternalAction();
        }
      } else {
        form.value['deliverySetting']['deepBidType'] = 'ROI_COEFFICIENT';
        form.value['deliverySetting']['cpaBid'] = null;
        awemeDeepSet();
        awemeSetDeepList();
      }
    });
  },
  {
    immediate: true
  }
);

/**
 * 监听优化目标变化
 *
 * 如果优化目标为关键行为则隐藏深度优化目标
 *
 * */
watch(
  () => form.value['optimizeGoal']['externalAction'],
  (newVal) => {
    nextTick(() => {
      // console.log('newval', newVal, externalActionListRes.value);
      if (form.value['microPromotionType'] !== 'AWEME') {
        if (newVal === 'TYPE_GAME_ADDICTION') {
          //如果优化目标为关键行为则隐藏深度优化目标
          form.value['optimizeGoal']['deepExternalAction'] = null;
        } else {
          if (newVal) {
            config.value.map((item) => {
              item.list.map((subitem, subindex) => {
                if (subitem.field === 'deepExternalAction') {
                  subitem.list = [];
                  // form.value[subitem.supField][subitem.field] = null;
                  subitem.list = externalActionListRes.value?.goals.flatMap((eitem) => {
                    return handleList(eitem.deepGoals);
                  });
                }
              });
            });
          }
        }
      } else {
        awemeSetDeepList();
      }
    });
  }
);
/**
 * 监听优化目标数据变化
 */
watch(
  () => externalActionListRes.value,
  () => {
    if (form.value['microPromotionType'] !== 'AWEME') {
      config.value.map((item) => {
        item.list.map((subitem, subindex) => {
          if (subitem.field === 'deepExternalAction') {
            subitem.list = [];
            // form.value[subitem.supField][subitem.field] = null;
            subitem.list = externalActionListRes.value?.goals.flatMap((eitem) => {
              return handleList(eitem.deepGoals);
            });
          }
        });
      });
    } else {
      awemeSetDeepList();
    }
  },
  { deep: true }
);

// 监听城市选择变化，更新全选状态
watch(
  () => form.value.audience.city && form.value.audience.city != null,
  (newValues) => {
    isIndeterminate.value = newValues?.length > 0 && newValues?.length < addressList.value.length;
    addressIsAllValue.value = newValues?.length === addressList.value.length ? ['ALL'] : [];
  }
);

// 处理全选逻辑
const handleAllSelect = (value) => {
  if (value.includes('ALL')) {
    if (form.value.audience.city.length === addressList.value.length) {
      // 全选状态，取消全选
      form.value.audience.city = [];
      addressIsAllValue.value = [];
    } else {
      // 选择所有
      form.value.audience.city = addressList.value.map((item) => item.value);
      addressIsAllValue.value = ['ALL'];
    }
  } else {
    // 全选状态，取消全选
    form.value.audience.city = [];
    addressIsAllValue.value = [];
  }
};

const handleList = (listInfo): Option[] => {
  if (!listInfo) return [];
  return listInfo.map((item) => {
    return {
      label: item.optimizationName,
      value: item.deepExternalAction
    };
  });
};

/**
 * 获取小程序信息
 */
const getAppInfo = (val: SelectAppInfoType[]) => {
  form.value.userInfo = val;
  form.value.optimizeGoal.assetIds = null;
  // console.log('val==========================', val);
  emit('updateInfo', val);
  getExternalAction();
  // if (form.value.microPromotionType === 'BYTE_APP') {
  //   form.value.optimizeGoal.assetIds = [form.value.userInfo[0]['assetId']];
  //   console.log('val', val);
  // }
};

const addressInit = async () => {
  const res = await getAddressListInfo({
    accountId: appStore.accountId,
    advertiserId: props.userList[0]?.id,
    codes: ['CN'],
    subDistrict: 'ONE_LEVEL'
  });
  const temp = res.data.districts[0]['subDistricts'] || [];
  addressList.value = temp.map((item) => {
    return {
      label: item.name,
      value: item.geonameId
    };
  });
};

/**
 * 保存数据
 */
const submitData = async () => {
  //验证用户是否选择小程序
  if (form.value.microPromotionType === 'WECHAT_APP' || form.value.microPromotionType === 'BYTE_APP') {
    let isOk = true;
    form.value.userInfo?.map((item) => {
      if (!isOk) return;
      if (!item.appId) {
        isOk = false;
      }
    });
    if (!isOk) {
      proxy?.$modal.msgError('请选择小程序');
      return;
    }
  }
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.microAppInstanceId =
        form.value['microPromotionType'] !== 'AWEME' ? (form.value.userInfo ? form.value.userInfo[0].instanceId : null) : null;
      selectAges.value = selectAges.value.filter((item) => item.trim() !== '');
      form.value.audience.age = JSON.parse(JSON.stringify(selectAges.value));
      emit('getValue', form.value);
      hide();
    } else {
      proxy?.$modal.msgError('请完善信息');
    }
  });
};
const getMircoAppList = async () => {
  // loading.value = true;
  let params = {
    pageNum: 1,
    pageSize: 100,
    advertiserId: props.userList[0]?.id,
    accountId: appStore.accountId
  };
  let productListTemp = [];
  if (form.value['microPromotionType'] !== 'AWEME') {
    if (form.value['microPromotionType'] === 'WECHAT_APP') {
      const res = await getAllWechatApplet(params);
      productListTemp = res.data;
    } else {
      const res = await queryToolsMicroAppNew(params);
      productListTemp = res.data;
    }
    form.value.userInfo = [];
    productListTemp.forEach((itm) => {
      if (itm.instanceId == form.value?.microAppInstanceId) {
        form.value.userInfo.push({
          name: form.value.name,
          id: itm.advertiserId,
          appName: itm.name,
          appId: itm.appId,
          instanceId: itm.instanceId,
        });
      }
    });
  }
};

onMounted(() => {
  nextTick(() => {
    // props.project && (form.value = { ...props.project });
    addressInit();
    getMircoAppList();
    getExternalAction();
  });
});

const show = () => {
  dialog.visible = true;
};
const hide = () => {
  dialog.visible = false;
};

defineExpose({ show, hide });
</script>

<style lang="scss" scoped>
:deep(.el-drawer__body) {
  background-color: #f1f1f1 !important;
}
:deep(.el-drawer) {
  width: 45% !important;
}

.addressSelect {
  border: 1px solid #e8eaec;
  padding: 15px;
}
.userbox {
  border: 1px solid #e8eaec;
  .userheader {
    border-bottom: 1px solid #e8eaec;
    .col {
      border-right: 1px solid #e8eaec;
      &:last-child {
        border-right: 0px;
      }
    }
  }
  .list {
    border-bottom: 1px solid #e8eaec;
    &:last-child {
      border-bottom: 0;
    }
    .col {
      border-right: 1px solid #e8eaec;
      &:last-child {
        border-right: 0px;
      }
    }
  }
}

.block {
  background-color: #fff;
  border: 1px solid #e8eaec;
  border-radius: 8px;
  margin-top: 12px;
  .title {
    padding: 15px;
    border-bottom: 1px solid #e8eaec;
  }
  .subitembox {
    padding: 10px;
    .listbox {
      border-radius: 4px;
      .listItem {
        font-size: 12px;
        padding: 0 12px;
        min-width: 90px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #606266;
        cursor: pointer;
        border: 1px solid #e8eaec;
        border-right: 0px;
        transition: all 0.3s linear;
        &:hover {
          color: #197afb;
        }
        &:first-child {
          border-radius: 4px 0 0 4px;
        }
        &:last-child {
          border-right: 1px solid #e8eaec;
          border-radius: 0 4px 4px 0;
        }
        &.active {
          background-color: #d6eaff;
          border: 1px solid #197afb;
          color: #197afb;
        }
        &.onlyOne {
          border-radius: 4px !important;
        }
      }
    }
    .btn {
      padding: 0 12px;
      min-width: 90px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
